<?php
namespace App\Api\Controllers\Ad;


use App\Api\Controllers\BaseController;
use App\Models\Ad;
use App\Models\AppLogo;
use App\Models\Device;
use App\Models\Merchant;
use App\Models\Store;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AdController extends BaseController
{
    //广告列表
    public function ad_lists(Request $request)
    {
        try {
            $public = $this->parseToken();
            // $user_id = '';
            // if ($public->type == "merchant") {
            //     $user_id = $public->merchant_id;
            // }

            // if ($public->type == "user") {
            //     $user_id = $public->user_id;
            // }

            $obj = DB::table('ads');
            $store_id = $request->get('store_id', '');
            if ($store_id) {
                $obj->where('store_key_ids', $store_id);
            }

            $ad_url = $request->get('ad_url', '');

            if ($ad_url) {
                $obj->where("ad_url", "like", "%" . $ad_url . "%");
            }

            $obj->where('created_id', 2)
                ->orderBy('updated_at', 'desc');

            $this->message = '数据返回成功';
            $this->t = $obj->count();
            $data = $this->page($obj)->get();
            foreach ($data as $k=>$v){
                $store=DB::table('stores')->where('store_id', $v->store_key_ids)->first();
                $data[$k]->store_name=$store->store_name;
            }
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }

    }


    public function ad_create(Request $request)
    {
        try {
            $public = $this->parseToken();
            // $config_id = $public->config_id;
            // $user_id = '';
            // if ($public->type == "merchant") {
            //     $user_id = $public->merchant_id;
            // }
            // if ($public->type == "user") {
            //     $user_id = $public->user_id;
            // }

            // $ad_p_id = $request->get('ad_p_id', '');
            // $title = $request->get('title', '');
            // $ad_p_desc = $request->get('ad_p_desc', '');
            // $user_ids = $request->get('user_ids', '');
            $store_key_ids = $request->get('store_key_ids', '');
            // $s_time = $request->get('s_time', '');
            // $e_time = $request->get('e_time', '');
            // $imgs = $request->get('imgs', '');
            // $copy_content = $request->get('copy_content', '');
            $ad_url = $request->get('ad_url', '');
            // $ad_p_ids = explode(',', $ad_p_id);
            // $videos = $request->get('videos', '');

            if ($ad_url == "NULL") {
                $ad_url = "";
            }

            // $check_data = [
            //     'title' => '标题',
            //     'ad_p_id' => '位置',
            //     's_time' => '投放开始时间',
            //     'e_time' => '投放结束时间',
            //     'copy_content' => '复制内容',
            // ];
            // $check = $this->check_required($request->except(['token']), $check_data);
            // if ($check) {
            //     return json_encode([
            //         'status' => 2,
            //         'message' => $check
            //     ]);
            // }
            $array=array();
            $store_key_ids=explode(',',$store_key_ids);
            foreach ($store_key_ids as $k=>$v){
                 $store=DB::table('stores')->where('id',$v)->first();
                 $array[]=$store->store_id;
                 $sub_stores=DB::table('stores')->where('pid',$store->id)->get();
                 foreach ($sub_stores as $key=>$val){
                     $array[]=$val->store_id;
                 }
            }
            foreach ($array as $k => $v) {
                // $store=DB::table('stores')->where('id',$v)->first();
                $data = [
                    'title' => '',
                    'config_id' => '',
                    'ad_p_id' => '',
                    'model_type' => '',
                    'created_id' => '2',
                    'ad_p_desc' => '',
                    'user_ids' => '',
                    'store_key_ids' => $v,
                    's_time' => '',
                    'e_time' => '',
                    'imgs' => '',
                    'videos' => '',
                    'copy_content' => '',
                    'ad_url' => isset($ad_url) ? $ad_url : "",
                ];
                Ad::create($data);
            }

            return json_encode([
                'status' => 1,
                'message' => '添加成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    public function ad_up(Request $request)
    {
        try {
            $public = $this->parseToken();

            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
            }

            $id = $request->get('id', '');
            $ad_p_id = $request->get('ad_p_id', '');
            $title = $request->get('title', '');
            $ad_p_desc = $request->get('ad_p_desc', '');
            $user_ids = $request->get('user_ids', '');
            $store_key_ids = $request->get('store_key_ids', '');
            $s_time = $request->get('s_time', '');
            $e_time = $request->get('e_time', '');
            $imgs = $request->get('imgs', '');
            $copy_content = $request->get('copy_content', '');
            $ad_p_ids = explode(',', $ad_p_id);
            $ad_url = $request->get('ad_url', '');
            $videos = $request->get('videos', '');

            if (count($ad_p_ids) > 1) {
                return json_encode([
                    'status' => 2,
                    'message' => '修改不支持多个广告投放位置',
                ]);
            }

            if ($ad_url == "NULL") {
                $ad_url = "";
            }

            $data = [
                'title' => $title,
                'ad_p_id' => $ad_p_id,
                'model_type' => $public->type,
                'created_id' => $user_id,
                'ad_p_desc' => $ad_p_desc,
                'user_ids' => $user_ids,
                'store_key_ids' => $store_key_ids,
                's_time' => $s_time,
                'e_time' => $e_time,
                'imgs' => $imgs,
                'videos' => $videos,
                'copy_content' => $copy_content,
                'ad_url' => isset($ad_url) ? $ad_url : "",
            ];

            Ad::where('id', $id)->update($data);
            return json_encode([
                'status' => 1,
                'message' => '修改成功',
            ]);

        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    public function ad_del(Request $request)
    {
        try {
            $public = $this->parseToken();

            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
            }

            $id = $request->get('id', '');

            Ad::where('id', $id)->delete();

            return json_encode([
                'status' => 1,
                'message' => '删除成功',
            ]);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    public function ad_p_id(Request $request)
    {
        try {
            $public = $this->parseToken();
            $user_id = '';
            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
            }

            $data = [
                [
                    'ad_p_id' => '1',
                    'ad_p_desc' => '支付宝成功页  (建议上传尺寸:800*1280)'
                ],
                [
                    'ad_p_id' => '2',
                    'ad_p_desc' => '微信成功页  (建议上传尺寸:800*1280)'
                ],
                [
                    'ad_p_id' => '3',
                    'ad_p_desc' => '支付宝刷脸设备-支付后广告  (建议上传尺寸:640*428)'
                ],
                [
                    'ad_p_id' => '4',
                    'ad_p_desc' => '微信刷脸设备-支付后广告  (建议上传尺寸:640*428)'
                ],
                [
                    'ad_p_id' => '5',
                    'ad_p_desc' => '微信刷脸设备-青蛙  (建议上传尺寸:800*1280)'
                ],
//                [
//                    'ad_p_id' => '6',
//                    'ad_p_desc' => '微信刷脸设备-君时达  (建议上传尺寸:800*1280)'
//                ],
//                [
//                    'ad_p_id' => '7',
//                    'ad_p_desc' => '微信刷脸设备-织点  (建议上传尺寸:800*1280)'
//                ],
                [
                    'ad_p_id' => '8',
                    'ad_p_desc' => '支付宝刷脸设备-蜻蜓  (建议上传尺寸:800*1280)'
                ],
		[
                    'ad_p_id' => '9',
                    'ad_p_desc' => '微信双屏刷脸设备-pro'
                ]
            ];

            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    public function ad_info(Request $request)
    {
        try {
            $public = $this->parseToken();

            $id = $request->get('id', '');
            $ad = Ad::where('id', $id)->first();

            $user_ids = $ad->user_ids;
            $store_key_ids = $ad->store_key_ids;

            $user_ids_arr = explode(",", $user_ids);
            $store_key_ids_arr = explode(",", $store_key_ids);

            if ($public->type == "merchant") {
                $user_id = $public->merchant_id;
                $user = Merchant::whereIn('id', $user_ids_arr)
                    ->select('name')
                    ->get();
            }

            if ($public->type == "user") {
                $user_id = $public->user_id;
                $user = User::whereIn('id', $user_ids_arr)
                    ->select('name')
                    ->get();
            }

            $Store = Store::whereIn('id', $store_key_ids_arr)
                ->select('store_short_name')
                ->get();

            $user_names = '';
            if (!$user->isEmpty()) {
                foreach ($user as $k => $v) {
                    $user_names = $user_names . $v->name . ',';
                }
            }

            $store_names = '';
            if (!$Store->isEmpty()) {
                foreach ($Store as $k => $v) {
                    $store_names = $store_names . $v->store_short_name . ',';
                }
            }

            $ad->store_names = $store_names;
            $ad->user_names = $user_names;

            $this->message = '数据返回成功';
            return $this->format($ad);

        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    //广告列表
    public function ad_lists_new(Request $request)
    {
        $device_id = $request->get('DeviceId', ''); //设备号
        $device_type = $request->get('DeviceType', ''); //设备类型
        $ad_position = $request->get('AdPid', ''); //投放位置

        //设备是否存在
        $Device = Device::where('device_no', $device_id)
            ->where('device_type', $device_type)
            ->first();
        if (!$Device) {
            return json_encode([
                'status' => '2',
                'message' => '设备不存在'
            ]);
        }

        //门店是否存在
        $store_id = $Device->store_id;
        $store = Store::where('store_id', $store_id)
            ->select("status",'is_admin_close', 'id', 'is_delete', 'pid', 'is_close', 'user_id', 'config_id')
            ->first();
        if (!$store) {
            return json_encode([
                'status' => '2',
                'message' => '平台门店ID不正确'
            ]);
        }

        //关闭的商户禁止交易
        if ($store->is_close || $store->is_admin_close || $store->is_delete) {
            return json_encode([
                'status' => '2',
                'message' => '商户已经被服务商关闭,请联系客服'
            ]);
        }
        if($store->status!=1){
            return json_encode([
                'status' => '2',
                'message' => '商户已经被服务商关闭,请联系客服'
            ]);
        }
        try {
            $i = [1, 2, 3, 4];
            $users = [];
            $user_id = $store->user_id;
            $user_id_abc = $store->user_id;
            $store_key_id = $store->id;

            foreach ($i as $k => $v) {
                $user = User::where('id', $user_id_abc)
                    ->select('id', 'pid')
                    ->first();
                if ($user) {
                    $users[$k]['user_id'] = $user->id;
                    $user_id_abc = $user->pid;
                }
            }

            $e_time = date('Y-m-d H:i:s', time());
            $ad = Ad::whereIn('user_ids', $users)
                ->where('e_time', '>', $e_time)
                ->where('s_time', '<', $e_time)
                ->where('ad_p_id', $ad_position)
                ->orderBy('updated_at', 'desc')
                ->get();
            if ($ad->isEmpty()) {
                $ad = Ad::whereIn('created_id', $users)
                    ->where('e_time', '>', $e_time)
                    ->where('s_time', '<', $e_time)
                    ->where('ad_p_id', $ad_position)
                    ->orderBy('updated_at', 'desc')
                    ->get();
            }

            $i = 0;
            $j = 0;
            $ad_data1 = [];
            $ad_data2 = [];

            $logo_obj = AppLogo::where('config_id', '1234')
                ->select('ali_ad_default', 'wechat_ad_default')
                ->orderBy('updated_at', 'desc')
                ->first();
            if ($logo_obj) {
                if (in_array($ad_position, [1, 3, 8])) {
                    $logo_obj_url = $logo_obj->ali_ad_default;
                } else {
                    $logo_obj_url = $logo_obj->wechat_ad_default;
                }
            } else {
                $logo_obj_url = url('/ad1.png');
            }

            if ($ad != []) {
                foreach ($ad as $k => $value) {
                    $store_key_ids = $value->store_key_ids;
                    if ($store_key_ids) {
                        //设置门店ID
                        //查看此门店ID是否在这个里面
                        $store_key_ids_arr = explode(',', $store_key_ids);
                        if (!in_array($store_key_id, $store_key_ids_arr)) {
                            continue;
                        }
                    }

                    //范围是否设置代理商
                    $user_ids = $value->user_ids;
                    if ($user_ids) {
                        //查看此代理ID是否在这个里面
                        $user_ids_arr = explode(',', $user_ids);
                        if (!in_array($user_id, $user_ids_arr)) {
                            continue;
                        }
                    } else {
                        //没有设置代理 针对所有

                        //查看这个广告的创建者ID是谁 获取到他下面到所有代理商ID
                        $created_id = $value->created_id;
                        $user_ids_arr = $this->getSubIds($created_id);
                        if (!in_array($user_id, $user_ids_arr)) {
                            continue;
                        }
                    }

                    $imgs = json_decode($value->imgs, true);
                    $videos = json_decode($value->videos, true);

                    //图片
                    foreach ($imgs as $k1 => $v1) {
                        $i = $i + $k1;
                        $ad_data1[$i]['ad_file'] = $v1['img_url'];
                        $ad_data1[$i]['ad_url'] = $v1['click_url'];
                        $ad_data1[$i]['type'] = 'img';
                        $i += 1;
                    }

                    //视频
                    foreach ($videos as $k2 => $v2) {
                        $ad_data2[$j]['ad_file'] = $v2['img_url'];
                        $ad_data2[$j]['ad_url'] = $v2['click_url'];
                        $ad_data2[$j]['type'] = 'video';
                        $j += 1;
                    }
                }

                $ad_data = array_merge($ad_data1, $ad_data2);

                if (empty($ad_data) || ($ad_data == [])) {
                    $ad_data = [
                        [
                            'ad_file' => $logo_obj_url,
                            'ad_url' => url('/mb/login'),
                            'type' => 'img'
                        ]
                    ];
                }
            } else {
                $ad_data = [
                    [
                        'ad_file' => $logo_obj_url,
                        'ad_url' => url('/mb/login'),
                        'type' => 'img'
                    ]
                ];
            }

            return $this->format($ad_data);
        } catch (\Exception $ex) {
            Log::info('广告列表-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            $this->status = -1;
            $this->message = $ex->getMessage().' | '.$ex->getLine();
            return $this->format();
        }

    }


}

